package edu.whu;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * 启动程序类
 */
public class MiniApplicationContext {

    public static Map<String,Object> Start(String xmlName) throws BeanDefinitionException {
        Document document = getDocument(xmlName);
        return creatObject(document);
    }

    /**
     * 获取Docunment
     *
     * @param xmlName xml文件
     * @throws BeanDefinitionException 数据文件异常
     */
    public static Document getDocument(String xmlName) throws BeanDefinitionException {
        SAXReader saxReader = new SAXReader();
        try (InputStream is = MiniApplicationContext.class.getResourceAsStream(xmlName)) {
            if(is == null){
                throw new BeanDefinitionException(BeanDefinitionException.ErrorType.FILE_NOTFOUND,"文件为空，请检查文件是否存在");
            }
            Document document = saxReader.read(is);
            return document;

        } catch (IOException e) {
            throw new BeanDefinitionException(BeanDefinitionException.ErrorType.XML_READ_ERROR, "XML文件读取失败");
        } catch (DocumentException e) {
            throw new BeanDefinitionException(BeanDefinitionException.ErrorType.DOCUMENT_CREAT_ERROR,"Document创建失败");
        }
    }

    /**
     * 创建对象并且属性依赖注入
     * @param document document文件名
     * @return 对象名，对象的hash数组
     * @throws BeanDefinitionException 创建对象、属性依赖注入的各种异常
     */
    public static Map<String,Object> creatObject(Document document) throws BeanDefinitionException {
            //获取根节点
            Element root = document.getRootElement();
            Map<String,Object> map = new HashMap<>();
            //获取对应子节点
            List<Element> beanList = root.elements("bean");
            for(Element bean :beanList){
                String id = bean.attributeValue("id");
                String aClass = bean.attributeValue("class");
                //创建class对象
                Class<?> clazz = null;
                try {
                    clazz = Class.forName(aClass);
                } catch (ClassNotFoundException e) {
                    throw new BeanDefinitionException(BeanDefinitionException.ErrorType.CLASS_NOT_FOUND,"类不存在");
                }
                //创建对象
                Object obj = null;
                try {
                    obj = clazz.newInstance();
                } catch (InstantiationException e) {
                    throw new BeanDefinitionException(BeanDefinitionException.ErrorType.CREAT_OBJECT_ERROR,"创建对象失败：请检查是否有无参构造函数");
                } catch (IllegalAccessException e) {
                    throw new BeanDefinitionException(BeanDefinitionException.ErrorType.CREAT_OBJECT_ERROR,"创建对象失败：类不能是抽象类，无参构造函数不能为私有");
                }
                //setter方法属性依赖注入
                List<Element> paraElement = bean.elements("property");
                for (Element element : paraElement) {
                    String name = element.attributeValue("name");
                    String value = element.attributeValue("value");
                    try {
                        Field nameF = clazz.getDeclaredField(name);
                        //暴力调用set方法
                        nameF.setAccessible(true);
                        //利用正则表达式判断string能否转换成int类型
                        if(!value.matches("\\d+")){
                        nameF.set(obj,value);
                        }else{
                            nameF.set(obj,Integer.valueOf(value));
                        }
                    }catch (IllegalAccessException e) {
                        throw new BeanDefinitionException(BeanDefinitionException.ErrorType.NO_SETTER_METHOD,"该类没有对应的setter方法");
                    } catch (NoSuchFieldException e) {
                        throw new BeanDefinitionException(BeanDefinitionException.ErrorType.NO_SUCH_FIELD,"该类没有对应的字段");
                    }
                }
                //将创建的对象写入hashMap
                map.put(id,obj);
            }
            return map;
    }

}